import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/gestures.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/routes/routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  Timer _countdownTimer;
  String _codeCountdownStr = '获取验证码';
  int _countdownNum = 59;

  int selectedNum = 1;
  bool selectedType = false;

  //焦点
  FocusNode _focusNodeUserName = new FocusNode();
  FocusNode _focusNodePassWord = new FocusNode();
  FocusNode _focusPhone = new FocusNode();
  FocusNode _focusVode = new FocusNode();

  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _userNameController = new TextEditingController();
  TextEditingController _userPwdController = new TextEditingController();
  TextEditingController _userPhoneController = new TextEditingController();
  TextEditingController _userCodeController = new TextEditingController();

//  GlobalKey _formKey= new GlobalKey<FormState>();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  var _isShowClear = false; //是否显示输入框尾部的
  var _isShowClearPwd = false; //是否显示输入框尾部的
  var _isShowClearPhone = false; //是否显示输入框尾部的
  var _isShowClearVode = false; //是否显示输入框尾部的\
  var _showPwd = false;

  final TapGestureRecognizer private = TapGestureRecognizer();
  final TapGestureRecognizer userServer = TapGestureRecognizer();

  void authToQQ(BuildContext context) {
    SharesdkPlugin.getUserInfo(ShareSDKPlatforms.qq,
        (SSDKResponseState state, Map user, SSDKError error) {
      print(user);
      var qqInfo;
      if (Platform.isIOS) {
        qqInfo = user;
      } else {
        qqInfo = json.decode(user['dbInfo']);
      }
      qqPermit(qqInfo, context);
    });
  }

  void qqPermit(Map qqInfo, BuildContext context) {
    Provider.of<LoginViewModel>(context, listen: false).getQQPermit(qqInfo,
        onSuccess: (platform, openid, has_reg) {
      if (!has_reg) {
        Navigator.of(context).pushNamed(Routes.binding_phone,
            arguments: {'openid': openid, 'platform': platform});
      } else {
        Provider.of<LoginViewModel>(context, listen: false)
            .thirdPartLogin(platform, openid, onSuccess: () {
          Navigator.pop(context);
        });
      }
    });
  }

  void authToWechat(BuildContext context) {
    SharesdkPlugin.getUserInfo(ShareSDKPlatforms.wechatSession,
        (SSDKResponseState state, Map user, SSDKError error) {
      var wechatInfo;
      if (Platform.isIOS) {
        wechatInfo = user;
      } else {
        wechatInfo = json.decode(user['dbInfo']);
      }
      wechatPermit(wechatInfo, context);
    });
  }

  void wechatPermit(Map wechatInfo, BuildContext context) {
    Provider.of<LoginViewModel>(context, listen: false)
        .getWechatPermit(wechatInfo, onSuccess: (platform, openid, has_reg) {
      if (!has_reg) {
        Navigator.of(context).pushNamed(Routes.binding_phone,
            arguments: {'openid': openid, 'platform': platform});
      } else {
        Provider.of<LoginViewModel>(context, listen: false)
            .thirdPartLogin(platform, openid, onSuccess: () {
          Navigator.pop(context);
        });
      }
    });
  }

  void authToSina(BuildContext context) {
    SharesdkPlugin.getUserInfo(ShareSDKPlatforms.sina,
        (SSDKResponseState state, Map user, SSDKError error) {
      print(error);
      var sinaInfo;
      if (Platform.isIOS) {
        sinaInfo = user;
      } else {
        sinaInfo = json.decode(user['dbInfo']);
      }
      sinaPermit(sinaInfo, context);
    });
  }

  void sinaPermit(Map sinaInfo, BuildContext context) {
    Provider.of<LoginViewModel>(context, listen: false).getSinaPermit(sinaInfo,
        onSuccess: (platform, openid, has_reg) {
      if (!has_reg) {
        Navigator.of(context).pushNamed(Routes.binding_phone,
            arguments: {'openid': openid, 'platform': platform});
      } else {
        Provider.of<LoginViewModel>(context, listen: false)
            .thirdPartLogin(platform, openid, onSuccess: () {
          Navigator.pop(context);
        });
      }
    });
  }

  void authToApple(BuildContext context) {
    SharesdkPlugin.cancelAuth(ShareSDKPlatforms.apple,(SSDKResponseState state, Map user, SSDKError error) {
      print('清除apple token 成功');
    }).then((value) {
      SharesdkPlugin.getUserInfo(ShareSDKPlatforms.apple,
              (SSDKResponseState state, Map user, SSDKError error) {
            if(error.code == 200000) {
              Toast.show('Apple登录仅支持ios13+', context);
            } else {
              applePermit(user, context);
            }
          });
    });
  }

  void applePermit(Map appleInfo, BuildContext context) {
    Provider.of<LoginViewModel>(context, listen: false).getApplePermit(appleInfo,
        onSuccess: (platform, openid, has_reg) {
          if (!has_reg) {
            Navigator.of(context).pushNamed(Routes.binding_phone,
                arguments: {'openid': openid, 'platform': platform});
          } else {
            Provider.of<LoginViewModel>(context, listen: false)
                .thirdPartLogin(platform, openid, onSuccess: () {
              Navigator.pop(context);
            });
          }
        });
  }

  @override
  void initState() {
    private.onTap = () {
      Navigator.of(context).pushNamed(Routes.policy);
    };
    userServer.onTap = () {
      Navigator.of(context).pushNamed(Routes.agreement);
    };
    //设置焦点监听
    _focusNodeUserName.addListener(_focusNodeListener);
    _focusNodePassWord.addListener(_focusNodeListener);
    _focusPhone.addListener(_focusNodeListener);
    _focusVode.addListener(_focusNodeListener);
    //监听用户名框的输入改变
    _userNameController.addListener(() {
      print(_userNameController.text);
      errorName = null;
      errorMobile = null;
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userNameController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    _userPwdController.addListener(() {
      print(_userPwdController.text);
      errorPwd = null;
      errorMobile = null;
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPwdController.text.length > 0) {
        _isShowClearPwd = true;
      } else {
        _isShowClearPwd = false;
      }
      setState(() {});
    });
    _userPhoneController.addListener(() {
      print(_userPhoneController.text);
      errorMobile = null;
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPhoneController.text.length > 0) {
        _isShowClearPhone = true;
      } else {
        _isShowClearPhone = false;
      }
      setState(() {});
    });
    _userCodeController.addListener(() {
      print(_userCodeController.text);
      errorCode = null;

      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userCodeController.text.length > 0) {
        _isShowClearVode = true;
      } else {
        _isShowClearVode = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // 移除焦点监听
    _focusNodeUserName.removeListener(_focusNodeListener);
    _focusNodePassWord.removeListener(_focusNodeListener);
    _focusPhone.removeListener(_focusNodeListener);
    _focusVode.removeListener(_focusNodeListener);
    _userNameController.dispose();
    _userPwdController.dispose();
    _userPhoneController.dispose();
    _userCodeController.dispose();
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodeUserName.hasFocus) {
      print("用户名框获取焦点");
      // 取消密码框的焦点状态
      _focusNodePassWord.unfocus();
      _focusPhone.unfocus();
      _focusVode.unfocus();
    }
    if (_focusNodePassWord.hasFocus) {
      print("密码框获取焦点");
      // 取消用户名框焦点状态

      _focusNodeUserName.unfocus();
      _focusPhone.unfocus();
      _focusVode.unfocus();
      errorName = validateUserName(_userNameController.text);
    }
    if (_focusPhone.hasFocus) {
      print("手机号框获取焦点");
      // 取消用户名框焦点状态
      _focusNodePassWord.unfocus();
      _focusNodeUserName.unfocus();
      _focusVode.unfocus();
      errorPwd = validateUserPassword(_userPwdController.text);
    }
    if (_focusVode.hasFocus) {
      print("验证码框获取焦点");
      // 取消用户名框焦点状态
      (_formKey.currentState as FormState).reset();
      _focusNodePassWord.unfocus();
      _focusNodeUserName.unfocus();
      _focusPhone.unfocus();
      errorMobile = validateUserMobile(_userPhoneController.text);
    }
  }

  /**
   * 验证用户名
   */
  String validateUserName(value) {
    // 正则匹配用户名
    RegExp exp = RegExp(r'^[\u4e00-\u9fa5Za-z0-9_]+$');
    if (value.isEmpty) {
      return '用户名不能为空!';
    } else if (!exp.hasMatch(value)) {
      return '请输入正确用户名';
    }
    return null;
  }

  String validateUserPassword(value) {
    // 正则匹配用户名
    if (value.isEmpty || value.length < 6) {
      return '密码不能为空或小于六位';
    }
    return null;
  }

  String validateUserMobile(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (value.isEmpty) {
      return '手机号不能为空!';
    } else if (!exp.hasMatch(value)) {
      return '请输入正确手机号';
    }
    return null;
  }

  /**
   * 验证密码
   */
  String validateCode(String value) {
    if (value.isEmpty) {
      return '验证码不能为空';
    }
    return null;
  }

  var errorMobile;
  var errorName;
  var errorPwd;
  var errorCode;

  Widget bodyWidget() {
    return Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 50.h),
          child: Form(
            key: _formKey, //设置globalKey，用于后面获取FormState
            child: Column(
              children: <Widget>[
                new TextFormField(
                  style: TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
                  controller: _userNameController,
                  focusNode: _focusNodeUserName,
                  decoration: InputDecoration(
                    errorText: errorName,
                    errorStyle:
                        TextStyle(color: Color(0xFFFE0600), fontSize: 20.sp),
                    hintText: "用户名",
                    hintStyle:
                        TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮
                    suffixIcon: (_isShowClear)
                        ? IconButton(
                            icon: Icon(
                              Icons.cancel,
                              size: 27.sp,
                            ),
                            onPressed: () {
                              // 清空输入框内容
                              _userNameController.clear();
                            },
                          )
                        : null,
                  ),
                  validator: validateUserName,
                ),
                new TextFormField(
                  style: TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
                  controller: _userPwdController,
                  focusNode: _focusNodePassWord,
                  //设置键盘类型
                  obscureText: !_showPwd,
                  inputFormatters: [
                    LengthLimitingTextInputFormatter(16),
                  ],
                  decoration: InputDecoration(
                      errorText: errorPwd,
                      errorStyle:
                          TextStyle(color: Color(0xFFFE0600), fontSize: 20.sp),
                      hintText: "密码 (请输入至少6位)",
                      hintStyle:
                          TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮
                      suffixIcon: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          (_isShowClearPwd)
                              ? SizedBox(
                                  height: 18.0,
                                  width: 18.0,
                                  child: IconButton(
                                    padding: EdgeInsets.all(0),
                                    iconSize: 30.sp,
                                    icon: Icon(
                                      Icons.cancel,
                                      size: 27.sp,
                                    ),
                                    onPressed: () {
                                      // 清空输入框内容
                                      _userPwdController.clear();
                                    },
                                  ),
                                )
                              : Text(""),
                          SizedBox(
                            child: IconButton(
                              iconSize: 30.sp,
                              padding: EdgeInsets.all(0),
                              icon: Icon((_showPwd)
                                  ? Icons.visibility
                                  : Icons.visibility_off),
                              onPressed: () {
                                setState(() {
                                  _showPwd = !_showPwd;
                                });
                              },
                            ),
                          )
                        ],
                      )),
                  validator: validateUserPassword,
                ),
                new TextFormField(
                  style: TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
                  controller: _userPhoneController,
                  focusNode: _focusPhone,
                  //设置键盘类型
                  keyboardType: TextInputType.number,
                  inputFormatters: [
                    WhitelistingTextInputFormatter.digitsOnly,
                    //限制只允许输入数字
                    LengthLimitingTextInputFormatter(11),
                    //限制输入长度不超过8位
                  ],
                  decoration: InputDecoration(
                    errorText: errorMobile == "null" ? null : errorMobile,
                    errorStyle:
                        TextStyle(color: Color(0xFFFE0600), fontSize: 20.sp),
                    hintText: "手机号 (请输入11位手机号)",
                    hintStyle:
                        TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮
                    suffixIcon: (_isShowClearPhone)
                        ? IconButton(
                            icon: Icon(
                              Icons.cancel,
                              size: 27.sp,
                            ),
                            onPressed: () {
                              // 清空输入框内容
                              _userPhoneController.clear();
                            },
                          )
                        : null,
                  ),
                  validator: validateUserMobile,
                ),
                new TextFormField(
                    style: TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
                    controller: _userCodeController,
                    focusNode: _focusVode,
                    inputFormatters: [
//                    WhitelistingTextInputFormatter(RegExp("[a-z,A-Z,0-9]")),      //限制只允许输入字母和数字
                      WhitelistingTextInputFormatter.digitsOnly,
                      //限制只允许输入数字
                      LengthLimitingTextInputFormatter(6),
                      //限制输入长度不超过8位
                    ],
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                      errorText: errorCode,
                      errorStyle:
                          TextStyle(color: Color(0xFFFE0600), fontSize: 20.sp),
                      suffixIcon: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          (_isShowClearVode)
                              ? IconButton(
                                  icon: Icon(
                                    Icons.cancel,
                                    size: 27.sp,
                                  ),
                                  onPressed: () {
                                    // 清空输入框内容
                                    _userCodeController.clear();
                                  },
                                )
                              : Text(""),
                          Builder(
                              builder: (context) => FlatButton(
                                    onPressed: sendCode() ? send : null,
                                    child: Text(
                                      _codeCountdownStr,
                                      style: TextStyle(
                                          fontSize: 31.sp,
                                          color:
                                              Color.fromRGBO(130, 134, 142, 1)),
                                    ),
                                  ))
                        ],
                      ),
                      hintText: "请输入验证码",
                      hintStyle:
                          TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
                    ),
                    //验证码验证
                    validator: validateCode),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "已有账号？",
                      style:
                          TextStyle(fontSize: 25.sp, color: Color(0xFF82868E)),
                    ),
                    InkWell(
                      child: Text(
                        "去登录",
                        style: TextStyle(fontSize: 25.sp),
                      ),
                      onTap: () {
                        Navigator.pop(context);

                        Navigator.of(context).pushNamed(Routes.login_page);
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 180.h),
          width: 559.w,
          height: 96.h,
          color: Color(0xFF0CABCB),
          child: FlatButton(
            child: Text(
              '注册',
              style: TextStyle(fontSize: 30.sp, color: Color(0xFFF7F8F8)),
            ),
            onPressed: () {
              if (_formKey.currentState.validate()) {
                var model = context.read<LoginViewModel>();
                model.register(
                    _userNameController.text,
                    _userPwdController.text,
                    _userPhoneController.text,
                    _userCodeController.text,
                    selectedType, onSuccess: () {
                  Navigator.pop(context);
                  Navigator.pop(context);
                  selectedType == true
                      ? Navigator.of(context)
                          .pushNamed(Routes.attestation_type_company)
                      : null;
                }, onFail: (error) {
                  decideError(error);
                  _focusNodePassWord.unfocus();
                  _focusNodeUserName.unfocus();
                  _focusPhone.unfocus();
                  _focusVode.unfocus();
                });
              } else {
                _focusNodePassWord.unfocus();
                _focusNodeUserName.unfocus();
                _focusPhone.unfocus();
                _focusVode.unfocus();
              }
            },
          ),
        ),
        Container(
          width: double.infinity,
          margin: EdgeInsets.only(top: 120.h),
          child: Center(
            child: Text(
              "— 使用第三方账号登录 —",
              style: TextStyle(
                color: Color(0xFF82868E),
                fontSize: 28.sp,
              ),
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 40.h),
          child:  Platform.isIOS?
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              IconButton(
                icon: Image.asset(
                  "images/wechat.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToWechat(context);
                },
              ),
              IconButton(
                icon: Image.asset(
                  "images/share_qq.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToQQ(context);
                },
              ),
              IconButton(
                icon: Image.asset(
                  "images/share_weibo.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToSina(context);
                },
              ),
              IconButton(
                icon: Image.asset(
                  "images/share_apple.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToApple(context);
                },
              )
            ],
          ):
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              IconButton(
                icon: Image.asset(
                  "images/wechat.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToWechat(context);
                },
              ),
              IconButton(
                icon: Image.asset(
                  "images/share_qq.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToQQ(context);
                },
              ),
              IconButton(
                icon: Image.asset(
                  "images/share_weibo.png",
                  height: 60.h,
                  width: 69.w,
                ),
                onPressed: () {
                  authToSina(context);
                },
              ),
            ],
          )
        ),
        Container(
          margin: EdgeInsets.only(top: 120.h, bottom: 20.h),
          alignment: Alignment.bottomCenter,
          child: RichText(
              text: TextSpan(
                  text: '登录即同意LOXEN的',
                  style: TextStyle(color: Color(0xFFA0A0A0), fontSize: 25.sp),
                  children: <TextSpan>[
                TextSpan(
                    text: '《隐私政策》',
                    recognizer: private,
                    style:
                        TextStyle(color: Color(0xFF0CABCB), fontSize: 25.sp)),
                TextSpan(
                  text: '与',
                  style: TextStyle(color: Color(0xFFA0A0A0), fontSize: 25.sp),
                ),
                TextSpan(
                    text: '《用户协议》',
                    recognizer: userServer,
                    style: TextStyle(color: Color(0xFF0CABCB), fontSize: 25.sp))
              ])),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          '注册',
          style: TextStyle(
            fontSize: 32.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        brightness: Brightness.dark,
        leading: MySubassembly.getBackIcon(context, color: Colors.black),
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onPanStart: (_) {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: SingleChildScrollView(
          child: Container(
              padding: EdgeInsets.only(left: 94.w, right: 94.w),
              child: bodyWidget()),
        ),
      ),
    );
  }

  void reGetCountdown() {
    setState(() {
      if (_countdownTimer != null) {
        return;
      }
      // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。
      _codeCountdownStr = '${_countdownNum--}s后重新获取';
      _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdownNum > 0) {
            _codeCountdownStr = '${_countdownNum--}s后重新获取';
          } else {
            _codeCountdownStr = '获取验证码';
            _countdownNum = 59;
            _countdownTimer.cancel();
            _countdownTimer = null;
          }
        });
      });
    });
  }

  void decideError(String T) {
    setState(() {
      if (T.length > 1) {
        errorCode = T;
        return errorCode;
      }
    });
  }

  void send() {
    context.read<LoginViewModel>().code(_userPhoneController.text, "1",
        onSuccess: () {
      reGetCountdown();
    }, onFail: (error) {
      decideError(error);
    });
  }

  bool sendCode() {
    if (validateUserMobile(_userPhoneController.text) == null &&
        _countdownNum == 59) {
      errorMobile = null;
      return true;
    } else {
      errorMobile = validateUserMobile(_userPhoneController.text);
      return false;
    }
  }
}
